<?php

namespace addons\notice\controller;

use addons\notice\library\Service;
use addons\mplogin\model\Bind;
use app\admin\model\notice\AdminMptemplate;
use EasyWeChat\Factory;
use think\addons\Controller;
use think\Cache;
use think\Db;
use think\Log;

class Index extends Controller
{

    protected $noNeedLogin = ['*'];

    public function index()
    {
        $this->error("当前插件暂无前台页面");
    }


    // 公众号授权页面
    public function mpauth()
    {
        $mark = input('mark');
        $adminId = cache($mark);
        if (!$adminId) {
            $this->error('二维码已过期，请重新扫描', '', '', 99999);
        }

        if (!input('confirm')) {
            return $this->fetch();
        }
        $app = Service::getOfficialAccount();

        $url = addon_url('notice/index/getmpauth', ['mark' => input('mark')], true, true);

        $response = $app->oauth->scopes(['snsapi_userinfo'])
            ->redirect($url);
        //dump( $response );
        $url = $response->getTargetUrl();
        //dump($url);
        Header("Location: $url");
        exit();
    }
    public function mpauth2()
    {
        $mark = input('mark');
        $adminId = cache($mark);
        if (!$adminId) {
            $this->error('二维码已过期，请重新扫描', '', '', 99999);
        }

        if (!input('confirm')) {
            return $this->fetch();
        }
        $app = Service::getOfficialAccount();

        $url = addon_url('notice/index/getmpauth2', ['mark' => input('mark')], true, true);

        $response = $app->oauth->scopes(['snsapi_userinfo'])
            ->redirect($url);
        //dump( $response );
        $url = $response->getTargetUrl();
        //dump($url);
        Header("Location: $url");
        exit();
    }
    // 公众号授权获取用户信息
    public function getmpauth()
    {
        $app = Service::getOfficialAccount();
        $oauth = $app->oauth;
        $msg = '绑定成功';

        if (!defined('CAIJIAKU_ID')) {
            $res = getcaijiaku();
            if ($res['status'] == 0) {
                $this->error($res['msg']);
            }
        }
        // 获取 OAuth 授权结果用户信息

        $user = $oauth->user();
        $user = $user->toArray();
        $openid = $user['original']['openid'] ?? '';
        $nickname = $user['original']['nickname'] ?? '';
        $avatar = $user['original']['headimgurl'] ?? '';
        $unionid = $user['original']['unionid'] ?? '';

        $mark = input('mark');
        $adminId = cache($mark);
        if (!$adminId) {
            $this->error('二维码已过期，请重新扫描', '', '', 99999);
        }
        $exist = \app\admin\model\notice\AdminMptemplate::where('admin_id', $adminId)->find();
        if ($exist) {
            $msg = '该账号已被绑定过';
        } else {
            AdminMptemplate::create([
                'admin_id' => $adminId,
                'openid' => $openid,
                'nickname' => $nickname,
                'avatar' => $avatar,
                'unionid' => $unionid
            ]);
            //添加登录绑定
            Bind::bind($openid, $adminId);
        }
        Cache::rm($mark);

        $this->assign('msg', $msg);
        // 绑定后台账号
        return $this->fetch();
    }
    public function getmpauth2()
    {
        $app = Service::getOfficialAccount();
        $oauth = $app->oauth;
        $msg = '绑定成功';


        // 获取 OAuth 授权结果用户信息

        $user = $oauth->user();
        $user = $user->toArray();
        $openid = $user['original']['openid'] ?? '';
        $nickname = $user['original']['nickname'] ?? '';
        $avatar = $user['original']['headimgurl'] ?? '';
        $unionid = $user['original']['unionid'] ?? '';

        $mark = input('mark');
        $adminId = cache($mark);
        if (!$adminId) {
            $this->error('二维码已过期，请重新扫描');
        }
        //$exist = \app\admin\model\notice\AdminMptemplate::where('admin_id', $adminId)->find();
        $exist=Db::name('third2')->where('user_id',$adminId)->where('bindopenid2' , 1)->find();
        if ($exist) {
            $msg = '该账号已被绑定过';
            $this->error($msg);
        } else {
            $exist2=Db::name('third2')->where('user_id',$adminId)->find();
            $time = time();
            $values = [
                'user_id'       =>$adminId,
                'platform'      => $user['provider'],
                'apptype'       => 'mp',
                'unionid'       => $user['original']['unionid'],
                'openid'        => $openid,
                'openname'      => $nickname,
                'access_token'  => $user['access_token'],
                'refresh_token' => $user['refresh_token'],
                'expires_in'    => 7200,
                'createtime'    => $time,
                'updatetime'    => $time,
                'logintime'     => $time,
                'expiretime'    => $time + 7200,
            ];
            Db::name('third')->insertGetId($values);
            if($exist2){
                Db::name('third2')->where('user_id',$adminId)->data(['openid2'=>$openid,'openname2'=>$nickname,'bindopenid2' => 1])->update();
            }else{
                Db::name('third2')->insert(['openid2'=>$openid,'openname2'=>$nickname,'user_id'=>$adminId,'bindopenid2' => 1]);
            }
           
            //AdminMptemplate::create([
            //    'admin_id' => $adminId,
            //    'openid' => $openid,
            //    'nickname' => $nickname,
            //    'avatar' => $avatar,
            //    'unionid' => $unionid
            //]);
        }
        Cache::rm($mark);
        //$this->success($msg);
        $this->assign('msg', $msg);
        // 绑定后台账号
        return $this->fetch();
    }

    public function loginimage()
    {
        $mark = input('mark');
        $info = cache($mark);
        if (!$info) {
            $this->error('二维码已过期，请重新扫描', '', '', 99999);
        }

        if (!input('confirm')) {
            return $this->fetch();
        }
        $app = Service::getOfficialAccount();

        $url = addon_url('notice/index/getuserinfo', ['mark' => input('mark')], true, true);

        $response = $app->oauth->scopes(['snsapi_userinfo'])
            ->redirect($url);
        $url = $response->getTargetUrl();
        $file = cache($mark . "_url");
        if (file_exists($file)) {
            unlink($file); // 删除文件
        }
        Header("Location: $url");
        exit();
    }

    public function getuserinfo()
    {
        $app = Service::getOfficialAccount();
        $oauth = $app->oauth;
        $msg = '授权成功';

        // 获取 OAuth 授权结果用户信息
        $user = $oauth->user();
        if($user){
            $user = $user->toArray();
            $openid = $user['original']['openid'] ?? '';
            $nickname = $user['original']['nickname'] ?? '';
            $avatar = $user['original']['headimgurl'] ?? '';
            $unionid = $user['original']['unionid'] ?? '';

            $mark = input('mark');
            $info = cache($mark);
//            Log::error($info);
            if (!$info) {
                $msg = '二维码已过期，请刷新页面重新扫码';
            }
            if($info == "login"){
                $third = Db::name('third')->where(['openid'=>$openid])->find();
                if ($third) {
                    $this->auth->direct($third['user_id']);
                    $user = $this->auth->getUserinfo();
                    Cache::set($mark.'_userinfo',json_encode($user), 60 * 5);
                } else {
                    $msg = '未绑定的用户扫码,请在个人中心-我的资料-第三方账号管理进行绑定';
                }
            }else if($info == "register") {
                $third = Db::name('third')->where(['openid'=>$openid])->find();
                if ($third) {
                    $msg = '该微信号已注册！';
                }else {
                    // 将数组数据以JSON格式存储到Redis中，并设置过期时间为半小时
                    Cache::set($mark . '_registeruerinfo', json_encode($user), 1800); // 设置过期时间为1800秒（即半小时）
                    $msg = '扫码成功，请绑定手机号';
                }
            }else if($info == "XBG-AZSL"){ //安装算量扫码授权
                //判断有没有注册，跳转注册页面，还是直接跳转登录
                $third = Db::name('user_software')->where(['openid'=>$openid])->find();
                if($third && $third['thirdapp_zdx_az'] == 2){ //登录
                    // 将数组数据以JSON格式存储到Redis中，并设置过期时间为半小时
                    $user['saomaresult_type'] = 1; //1登录 2注册
                }else{  //注册
                    $user['saomaresult_type'] = 2; //1登录 2注册
                }
                Cache::set($mark . '_XBG-AZSL', json_encode($user), 1800); // 设置过期时间为1800秒（即半小时）
                $msg = '授权成功';
            }else if($info == "XBG-TJSL"){ //土建算量扫码授权
                //判断有没有注册，跳转注册页面，还是直接跳转登录
                $third = Db::name('user_software')->where(['openid'=>$openid])->find();
                if($third && $third['thirdapp_zdx_tj'] == 2){ //登录
                    // 将数组数据以JSON格式存储到Redis中，并设置过期时间为半小时
                    $user['saomaresult_type'] = 1; //1登录 2注册
                }else{  //注册
                    $user['saomaresult_type'] = 2; //1登录 2注册
                }
                Cache::set($mark . '_XBG-TJSL', json_encode($user), 1800); // 设置过期时间为1800秒（即半小时）
                $msg = '授权成功';
            }else if($info == "XBG-FWPT"){ //服务平台扫码
                $third = Db::name('third')->where(['openid'=>$openid])->find();
                if ($third) {
                    $this->auth->direct($third['user_id']);
                    $user = $this->auth->getUserinfo();
                    $user['saomaresult_type'] = 1; //1登录 2注册
                    Cache::set($mark.'_XBG-FWPT',json_encode($user), 60 * 5);
                } else {
                    $msg = '未绑定的用户扫码,请在材价通个人中心-我的资料-第三方账号管理进行绑定';
                }
            }
            Cache::rm($mark);
        }else{
            $msg = '您已取消授权';
        }

        $this->assign('msg', $msg);
        // 绑定后台账号
        return $this->fetch();
    }


}
